package com.example.tongyao.system.config;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.tongyao.system.entity.SysFreeAuth;
import com.example.tongyao.system.entity.SysUser;
import com.example.tongyao.system.service.ISysFreeAuthService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.List;

/**
 * TongYao2.0 >>> 【com.example.tongyao.system.config】
 * JWT 配置文件
 *
 * @author: tongyao
 * @since: 2021-08-01 17:47
 */
@Configuration
public class JwtConfig implements WebMvcConfigurer{

    @Value("${api.token.path}")
    String apiPath;

    @Value("${api.path.model}")
    String model;

    @Resource
    private ISysFreeAuthService iSysFreeAuthService;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注册TestInterceptor拦截器
        InterceptorRegistration registration = registry.addInterceptor(jwtInterceptor());

        if(model.equals("config")){
            //使用配置器里的
            String[] path = apiPath.split(",");
            for(String strPath : path){
                registration.excludePathPatterns(strPath);
            }
        }else if(model.equals("database")){
            //使用数据里的
            LambdaQueryWrapper<SysFreeAuth> sysFreeAuthLambdaQueryWrapper = new LambdaQueryWrapper<>();
            sysFreeAuthLambdaQueryWrapper.eq(SysFreeAuth::getPathType,"free_token");
            sysFreeAuthLambdaQueryWrapper.eq(SysFreeAuth::getDelFlag,"1");
            List<SysFreeAuth> sysFreeAuthList =iSysFreeAuthService.list(sysFreeAuthLambdaQueryWrapper);

            for(SysFreeAuth sysFreeAuth : sysFreeAuthList){
                registration.excludePathPatterns(sysFreeAuth.getPathAddress());
            }
        }else{
            throw new RuntimeException("获取jwt权限出错！！请查看配置文件！");
        }

        /*需要授权在才能跳转*/
        registration.addPathPatterns("/**");
    }
    @Bean
    public JwtInterceptor jwtInterceptor() {
        return new JwtInterceptor();
    }
}
